﻿using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using System.Windows.Media;
using CloudMusic.Helper;
using CloudMusic.Model;
using CloudMusic.ViewModel;
using DMSkin.Core.Common;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace CloudMusic.API
{
     class PlayManager
    {
        public static PlayState State { get; internal set; }
        public static MediaPlayer player;
        /// <summary>
        /// 播放  type-0（本地），1（网络）
        /// </summary>
        /// <param name="music"></param>
        internal static void Play(PlayModel music)
        {
            State = PlayState.Play;
            if (music.Type == 0)
            {
                if (music.Url.Contains("http"))
                {
                    if (!File.Exists(music.FileName))
                    {
                        Task.Run(() =>
                        {
                            music.DownLoad = true;
                            using (WebClient wb = new WebClient())
                            {
                                wb.DownloadFile(music.Url, music.FileName);
                            }
                            music.DownLoad = false;
                            music.Url = music.FileName;
                            Open(music);
                        });
                        return;
                    }
                    else
                    {
                        music.Url = music.FileName;
                    }
                }
            }
            else
            {
                var strJosn = CommonHelper.Get("http://localhost:3000/song/url?id=" + music.Id);
                JObject obj = (JObject)JsonConvert.DeserializeObject(strJosn);
                string data = obj["data"][0].ToString();
                JObject Data = (JObject)JsonConvert.DeserializeObject(data);
                music.Url = Data["url"].ToString();
            }
            Open(music);
        }
        /// <summary>
        /// 播放音量媒体
        /// </summary>
        /// <param name="music"></param>
        public static void Open(PlayModel music)
        {
            Execute.OnUIThread(() =>
            {
                player.Open(new Uri(music.Url, UriKind.RelativeOrAbsolute));
                player.Play();
            });
        }
        /// <summary>
        /// 音量调节
        /// </summary>
        /// <param name="DStr"></param>
        public static void VolumeChange(double DStr) 
        {
            player.Volume = DStr;

        }
        /// <summary>
        /// 播放进度调节
        /// </summary>
        /// <param name="DStr"></param>
        public static void PositionChange(double DStr)
        {
            player.Position = TimeSpan.FromSeconds(DStr);
        }
        /// <summary>
        /// 音量状态-静音/正常
        /// </summary>
        /// <param name="flag"></param>
        public static void ChangeVolumeState(bool flag) 
        {
            player.IsMuted = flag;
        }
    }
}
